package fun.fykj.liu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.fykj.liu.dto.ClockIn;
import fun.fykj.liu.dto.RecordOut;
import fun.fykj.liu.entity.Record;
import fun.fykj.liu.enums.ResCodeEnum;
import fun.fykj.liu.mapper.RecordMapper;
import fun.fykj.liu.model.Result;
import fun.fykj.liu.service.IRecordService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DongJin
 * @since 2020-01-16
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {

    @Override
    public Result getNotByDay(String day) {
        ArrayList<RecordOut> recordOuts = baseMapper.getNotByDay(day);
        return Result.ok(recordOuts);
    }

    @Override
    public Result clock(ClockIn clockIn) {
        //查询是否存在
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        wrapper.eq("day", clockIn.getDay());
        Record record = baseMapper.selectOne(wrapper);
        if (null != record) {
            String userIds = record.getUserIds();
            List<String> userIdList = Arrays.asList(userIds.split(""));
            if (userIdList.contains(clockIn.getId()))
                return Result.ok();
            userIds = userIds + "," + clockIn.getId();
            record.setUserIds(userIds);
        } else {
            record = new Record() {{
                setUserIds(clockIn.getId() + "");
                setDay(clockIn.getDay());
            }};
        }
        boolean b = saveOrUpdate(record);
        if (b)
            return Result.ok();
        else
            return Result.build(ResCodeEnum.SAVE_FAIL);
    }

    @Override
    public Result deleteBefore() {
        //删除昨日以前的记录
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -2);
        date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = format.format(date);
        System.out.println(dateString);
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        wrapper.le("day", dateString);
        boolean remove = remove(wrapper);
        System.out.println(remove);
        return Result.ok(remove);
    }
}
